"""
Verify AIPPT Create Task API
Test creating PPT tasks with different types
"""
import sys
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Add project root to path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from src.llm.aippt_app.utils.api_client import AIPPTAPIClient
from src.llm.aippt_app.config.aippt_config import AIPPTConfig


# Verify configuration
if not os.getenv("AIPPT_TOKEN"):
    print("ERROR: AIPPT_TOKEN not found in environment variables")
    print("Please set AIPPT_TOKEN in .env file")
    sys.exit(1)


def print_section(title: str):
    """Print section header"""
    print("\n" + "=" * 60)
    print(f"  {title}")
    print("=" * 60)


def test_create_task_type1_smart_generation():
    """Test Type 1: Smart Generation (theme/requirements)"""
    print_section("Test 1: Create Task - Smart Generation (Type 1)")

    client = AIPPTAPIClient()

    # Type 1: Smart generation with theme
    content = "AI Artificial Intelligence Development Trends and Applications"

    print(f"Content: {content}")
    print(f"Type: 1 (Smart Generation)")

    try:
        response = client.create_task(
            task_type=1,
            content=content
        )

        print(f"\nAPI Response:")
        print(f"Code: {response.get('code')}")
        print(f"Message: {response.get('message')}")

        if response.get('code') == 0:
            data = response.get('data', {})
            task_id = data.get('id')
            print(f"Task ID: {task_id}")
            print("\n[SUCCESS] Task created successfully!")
            return task_id
        else:
            print(f"\n[FAILED] API returned error code: {response.get('code')}")
            return None

    except Exception as e:
        print(f"\n[ERROR] Exception occurred: {str(e)}")
        return None


def test_create_task_type6_paste_text():
    """Test Type 6: Paste Text Content"""
    print_section("Test 2: Create Task - Paste Text (Type 6)")

    client = AIPPTAPIClient()

    # Type 6: Paste text content
    content = """
Artificial Intelligence Development Trends

1. Machine Learning and Deep Learning
   - Neural networks continue to evolve
   - More efficient training methods
   - Edge AI deployment

2. Natural Language Processing
   - Large language models (LLMs)
   - Multimodal capabilities
   - Real-time translation

3. Computer Vision
   - Object detection and recognition
   - Image generation
   - Video analysis

4. AI Ethics and Governance
   - Responsible AI development
   - Bias detection and mitigation
   - Privacy protection
"""

    print(f"Content length: {len(content)} characters")
    print(f"Type: 6 (Paste Text)")
    print(f"Content preview: {content[:100]}...")

    try:
        response = client.create_task(
            task_type=6,
            content=content
        )

        print(f"\nAPI Response:")
        print(f"Code: {response.get('code')}")
        print(f"Message: {response.get('message')}")

        if response.get('code') == 0:
            data = response.get('data', {})
            task_id = data.get('id')
            print(f"Task ID: {task_id}")
            print("\n[SUCCESS] Task created successfully!")
            return task_id
        else:
            print(f"\n[FAILED] API returned error code: {response.get('code')}")
            return None

    except Exception as e:
        print(f"\n[ERROR] Exception occurred: {str(e)}")
        return None


def test_create_task_type7_markdown():
    """Test Type 7: Markdown Outline"""
    print_section("Test 3: Create Task - Markdown Outline (Type 7)")

    client = AIPPTAPIClient()

    # Type 7: Markdown outline
    content = """
# AI Development Trends

## Introduction
- Overview of AI
- Current state of technology

## Machine Learning
### Deep Learning
- Neural networks
- Training methods

### Applications
- Image recognition
- Natural language processing

## Future Outlook
- Emerging technologies
- Challenges and opportunities
"""

    print(f"Content length: {len(content)} characters")
    print(f"Type: 7 (Markdown Outline)")
    print(f"Content preview:\n{content[:150]}...")

    try:
        response = client.create_task(
            task_type=7,
            content=content
        )

        print(f"\nAPI Response:")
        print(f"Code: {response.get('code')}")
        print(f"Message: {response.get('message')}")

        if response.get('code') == 0:
            data = response.get('data', {})
            task_id = data.get('id')
            print(f"Task ID: {task_id}")
            print("\n[SUCCESS] Task created successfully!")
            return task_id
        else:
            print(f"\n[FAILED] API returned error code: {response.get('code')}")
            return None

    except Exception as e:
        print(f"\n[ERROR] Exception occurred: {str(e)}")
        return None


def test_create_task_type5_web_link():
    """Test Type 5: Web Link"""
    print_section("Test 4: Create Task - Web Link (Type 5)")

    client = AIPPTAPIClient()

    # Type 5: Web link
    content = "https://en.wikipedia.org/wiki/Artificial_intelligence"

    print(f"Content: {content}")
    print(f"Type: 5 (Web Link)")

    try:
        response = client.create_task(
            task_type=5,
            content=content
        )

        print(f"\nAPI Response:")
        print(f"Code: {response.get('code')}")
        print(f"Message: {response.get('message')}")

        if response.get('code') == 0:
            data = response.get('data', {})
            task_id = data.get('id')
            print(f"Task ID: {task_id}")
            print("\n[SUCCESS] Task created successfully!")
            return task_id
        else:
            print(f"\n[FAILED] API returned error code: {response.get('code')}")
            return None

    except Exception as e:
        print(f"\n[ERROR] Exception occurred: {str(e)}")
        return None


def main():
    """Main test function"""
    print("\n" + "=" * 60)
    print("  AIPPT Create Task API Verification")
    print("=" * 60)
    print("\nTesting different task types according to API docs:")
    print("Type 1: Smart Generation (theme/requirements)")
    print("Type 2: Upload File")
    print("Type 3: Mind Map")
    print("Type 4: Word to PPT")
    print("Type 5: Web Link")
    print("Type 6: Paste Text")
    print("Type 7: Markdown Outline")

    results = []

    # Test Type 1: Smart Generation
    task_id_1 = test_create_task_type1_smart_generation()
    results.append(("Type 1 - Smart Generation", task_id_1 is not None, task_id_1))

    # Test Type 6: Paste Text
    task_id_6 = test_create_task_type6_paste_text()
    results.append(("Type 6 - Paste Text", task_id_6 is not None, task_id_6))

    # Test Type 7: Markdown
    task_id_7 = test_create_task_type7_markdown()
    results.append(("Type 7 - Markdown", task_id_7 is not None, task_id_7))

    # Test Type 5: Web Link
    task_id_5 = test_create_task_type5_web_link()
    results.append(("Type 5 - Web Link", task_id_5 is not None, task_id_5))

    # Summary
    print_section("Test Summary")
    print(f"\nTotal tests: {len(results)}")
    passed = sum(1 for _, success, _ in results if success)
    failed = len(results) - passed
    print(f"Passed: {passed}")
    print(f"Failed: {failed}")

    print("\nDetailed Results:")
    for test_name, success, task_id in results:
        status = "[PASS]" if success else "[FAIL]"
        print(f"{status} {test_name}")
        if task_id:
            print(f"       Task ID: {task_id}")

    if passed == len(results):
        print("\n[SUCCESS] All tests passed!")
    else:
        print(f"\n[WARNING] {failed} test(s) failed")


if __name__ == "__main__":
    main()
